package dao

import (
	"github.com/jinzhu/gorm"
	"time"
)

type Zone struct {
	Zid int `json:"z_id" gorm:"column:z_id""`
	Uid int `json:"uid"`
	ZoneUuid string `json:"zone_uuid" gorm:"column:zone_uuid"`
	Name string `json:"name" gorm:"column:name"`
	Desc string `json:"desc" gorm:"column:description"`
	State string `json:"state" gorm:"column:state"`
	Type string `json:"type" gorm:"column:type"`
	Ctime int64 `json:"c_time" gorm:"column:c_time"`
	Dtime int64 `json:"d_time" gorm:"column:d_time"`
}
func (t *Zone) Create(d map[string]interface{}) (bool,int) {

	var az Zone
	if v,ok := d["uuid"];ok{
		az.ZoneUuid = v.(string)
	}
	if v,ok := d["name"];ok{
		az.Name = v.(string)
	}
	if v,ok := d["description"];ok{
		az.Desc = v.(string)
	}
	if v,ok := d["state"];ok{
		az.State = v.(string)
	}
	if v,ok := d["type"];ok{
		az.Type = v.(string)
	}
	az.Ctime = time.Now().Unix()
	az.Uid = d["uid"].(int)
	b := true
	err := db.Create(&az).Error
	if err != nil{
		b = false
	}
	var id []int
	db.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id)
	return b,id[0]
}
/**
	软删除
 */
func (t *Zone)Delete(w map[string]interface{}) bool {

	upd := Zone{
		Dtime:time.Now().Unix(),
	}
	err := db.Model(&t).Where(w).Update(upd).Error
	b := true
	if err != nil{
		b = false
	}
	return b

}
func (t *Zone)Update(w map[string]interface{},f map[string]interface{}) bool {

	fs := &Zone{}
	if v,ok := f["name"];ok{
		fs.Name = v.(string)
	}
	if v,ok := f["description"];ok{
		fs.Desc = v.(string)
	}
	b := true
	err := db.Model(&t).Where(w).Updates(&fs).Error
	if err != nil{
		b = false
	}
	return b

}
func (t *Zone)UpdateState(w map[string]interface{},f map[string]interface{}) bool {
	fs := &Zone{}
	if v,ok := f["state"];ok{
		fs.State = v.(string)
	}
	b := true
	err := db.Model(&t).Where(w).Updates(&fs).Error
	if err != nil{
		b = false
	}
	return b
}
func (t *Zone)Find(w map[string]interface{},page int,pageSize int)([]*Zone,int,error){

	var total int = 0
	var us []*Zone
	// 获取取指page，指定pagesize的记录
	err := db.Where(w).
		Where("d_time = ?",0).
		Limit(pageSize).Offset((page-1)*pageSize).
		Order("z_id desc").Find(&us).Error
	if err != nil && err != gorm.ErrRecordNotFound{
		return nil ,0,err
	}

	// 获取总条数
	db.Model(&t).Where(w).Where("d_time=?",0).Count(&total)

	if err != nil && err != gorm.ErrRecordNotFound{
		return nil ,0,err
	}
	return us,total,nil

}
func (t *Zone)First(uuid string) (error, *Zone){
	err :=db.Where("zone_uuid = ?",uuid).First(&t).Error
	if err != nil{
		return err,nil
	}
	if t.Zid > 0{
		return err,t
	}
	return nil,t
}
var ZoneD = &Zone{}

